package com.pdsu.alumni.controller;


import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import com.pdsu.alumni.common.annotation.NoAuthentication;
import com.pdsu.alumni.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Api(tags = "文件操作")
@RestController//返回JSON
@RequestMapping("/file")
public class FilesController {
    @Value("${server.port}")
    private String port;
    //服务器ip
    //private static final String ip = "http://121.36.73.32";
    //本地ip
    private static final String ip = "http://121.36.73.32";

    @ApiOperation(value = "文件上传")
    @NoAuthentication
    @CrossOrigin
    @PostMapping("/upload")
    public Result<?> upload(@RequestPart("file") MultipartFile file) throws IOException {

        String filename = file.getOriginalFilename();   //获取文件名称
        //定义唯一标识符
        String uuid = IdUtil.fastSimpleUUID();
        //服务器目录
        String filePath = "/www\\wwwroot\\alumni\\";
        //本地目录,陈雅楠,你,改这里就行
        //String filePath = "/C:\\Users\\Acerola\\Desktop\\images\\";
        String rootFilePath = filePath + uuid + "_" + filename;  //获取文件存储路劲
        FileUtil.writeBytes(file.getBytes(), rootFilePath);
        Map map = new HashMap<>();
        Map fileList = new HashMap<>();
        fileList.put("uid", "-1");
        fileList.put("name", filename);
        fileList.put("status", "done");
        fileList.put("url", ip + ":" + port + "/file/" + uuid);
        fileList.put("thumbUrl", ip + ":" + port + "/file/" + uuid);

        map.put("fileList", fileList);
        return new Result().success("上传成功").put(map);
    }

    @ApiOperation(value = "")
    @NoAuthentication
    @CrossOrigin
    @PostMapping("/editor/upload")
    public JSON editor(@RequestPart("file") MultipartFile file) throws IOException {
        String filename = file.getOriginalFilename();   //获取文件名称
        //定义唯一标识符
        String uuid = IdUtil.fastSimpleUUID();
//      String rootFilePath = "/C:\\Users\\Acerola\\Desktop\\images\\" + uuid + "_" + filename;  //获取文件存储路劲
        //孙
        //String rootFilePath = "C:\\Users\\Acerola\\Desktop\\images\\" + uuid + "_" + filename;  //获取文件存储路劲
        String rootFilePath = "/www\\wwwroot\\alumni\\" + uuid + "_" + filename;  //获取文件存储路劲
        FileUtil.writeBytes(file.getBytes(), rootFilePath);
        String url = ip + ":" + port + "/file/" + uuid;
        JSONObject json = new JSONObject();
        json.set("errno", 0);
        JSONArray array = new JSONArray();
        JSONObject data = new JSONObject();
        array.add(data);
        data.set("url", url);
        json.set("data", array);
        return json;
    }

    @ApiOperation(value = "文件下载")
    @NoAuthentication
    @CrossOrigin
    @GetMapping("/{flag}")
    public Result<?> getFiles(@PathVariable String flag, HttpServletResponse response) {
        OutputStream os;  // 新建一个输出流对象
        //String basePath = "/usr/local/uploadfilework/";  // 定于文件上传的根路径
        //String basePath = "/C:\\Users\\Acerola\\Desktop\\images\\";
        //孙
        //String basePath = "C:\\Users\\Acerola\\Desktop\\images\\";
        String basePath = "/www\\wwwroot\\alumni\\";
        List<String> fileNames = FileUtil.listFileNames(basePath);  // 获取所有的文件名称
        String fileName = fileNames.stream().filter(name -> name.contains(flag)).findAny().orElse("");  // 找到跟参数一致的文件
        try {
            if (StrUtil.isNotEmpty(fileName)) {
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                response.setContentType("application/octet-stream");
                byte[] bytes = FileUtil.readBytes(basePath + fileName);  // 通过文件的路径读取文件字节流
                os = response.getOutputStream();   // 通过输出流返回文件
                os.write(bytes);
                os.flush();
                os.close();
            }
        } catch (Exception e) {
            return new Result<>().error("文件下载失败");
        }
        return new Result<>().success("文件下载成功");
    }

}

